package Demo;

import com.qf.model.newUser;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@SpringBootTest
public class Demo {
    @Test
    public void demo(){
        newUser user = new newUser("1",20,50);
        newUser user1 = new newUser("2",21,40);
        newUser user2 = new newUser("3",21,45);
        newUser user3 = new newUser("4",22,46);
        newUser user4 = new newUser("5",22,85);
        newUser user5 = new newUser("6",20,60);
        newUser user6 = new newUser("7",23,55);
        newUser user7 = new newUser("8",23,69);
        newUser user8 = new newUser("9",26,42);
//        newUser user9 = new newUser(null,25,48);

        //动态添加元素，转成list
        List<newUser>  userList =
                Stream.of(user,user1,user2,user3,user4,user5,user6,user7,user8).collect(Collectors.toList());

        //取对象的某一列 通过map将对象的某一列转成集合
        List<String> nameList = userList.stream().map(newUser::getName).collect(Collectors.toList());

        //遍历
        //  nameList.stream().forEach(o-> System.out.println(o));

        //过滤 筛选出userList中name不为空的user
        List<newUser>  userList1 = userList.stream().filter(newUser -> newUser.getName() != null).collect(Collectors.toList());
        List<newUser>  userList2 = userList.stream().filter(newUser -> newUser.getAge() > 20).filter(newUser -> newUser.getHeight()>40).collect(Collectors.toList());

        //把userList中的user根据年龄分组,相同的放在一起
        Map<Integer, List<newUser>> map =userList.stream().collect( Collectors.groupingBy(newUser::getAge, Collectors.toList()));

        //求和
        // int、double、long:
        Integer sum = userList.stream().mapToInt(newUser::getAge).sum();

        //最大/小值
        Optional<newUser> max = userList.stream().collect(Collectors.maxBy(Comparator.comparing(newUser::getAge)));
        Optional<newUser> min = userList.stream().collect(Collectors.minBy(Comparator.comparing(newUser::getAge)));

        //平均值
        Integer AvgAge = userList.stream().collect(Collectors.summingInt(newUser::getHeight));

        //Map、List互转
        //list----> map
        Map<String, newUser> userMap= userList.stream().collect(Collectors.toMap(newUser::getName, Function.identity(),(key1, key2)->key2));























    }

}
